﻿using System;
using System.Xml.Linq;
using System.Xml.XPath;
using Kaleida.ServiceMonitor.Framework;

namespace Kaleida.ServiceMonitor.Operations.PreparedRequests
{
    public class CcnetBuild : PreparedRequest
    {
        private readonly Uri serverUri;
        private readonly string projectName;

        public CcnetBuild(string serverUri, string projectName)
        {
            if (serverUri == null) throw new ArgumentNullException("serverUri");
            if (serverUri.Trim() == "") throw new ArgumentException("Cannot be blank", "serverUri");

            if (projectName == null) throw new ArgumentNullException("projectName");
            if (projectName.Trim() == "") throw new ArgumentException("Cannot be blank", "projectName");

            this.serverUri = new Uri(serverUri.EndsWith("/") ? serverUri : serverUri + "/");
            this.projectName = projectName;
        }

        public override object GetResponse()
        {
            var xmlReportUri = XmlReportUri;

            var doc = XDocument.Load(xmlReportUri.ToString());

            var projectElements = doc.XPathSelectElement(string.Format("/Projects/Project[@name='{0}']", projectName));

            var lastBuildStatusAttribute = projectElements.Attribute("lastBuildStatus");

            if (lastBuildStatusAttribute == null)
                throw new InvalidOperationException("lastBuildStatus attribute was null");

            return lastBuildStatusAttribute.Value;
        }

        private Uri XmlReportUri
        {
            get
            {
                return new Uri(serverUri, "XmlStatusReport.aspx");
            }
        }

        public override string Description
        {
            get { return string.Format("Get the CruiseControl.NET build status from '{0}' for project '{1}'", XmlReportUri, projectName); }
        }
    }
}
